package io.bhex.app.hardware;

import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;
import java.util.List;

import io.bhex.baselib.utils.DebugLog;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2019-11-14
 * 邮   箱：
 * 描   述：
 * ================================================
 */

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";
    private final Camera.Parameters parameters;
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        parameters = mCamera.getParameters();
    }

    public void surfaceCreated(SurfaceHolder holder) {
        if (getResources().getConfiguration().orientation!= Configuration.ORIENTATION_LANDSCAPE){
            parameters.set("orientation","portrait");
            mCamera.setDisplayOrientation(90);
            //在exif数据中，旋转90°
            parameters.setRotation(90);
        }else {
            parameters.set("orientation","landscape");
            mCamera.setDisplayOrientation(0);
            //在exif数据中，旋转0°
            parameters.setRotation(0);
        }

        //设置Camera预览的大小
        Camera.Size previewSize = getPropPreviewSize(parameters.getSupportedPreviewSizes());
        parameters.setPreviewSize(previewSize.width,previewSize.height);

        // 通知摄像头可以在这里绘制预览了
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            DebugLog.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // 什么都不做，但是在Activity中Camera要正确地释放预览视图
    }

    /**
     * 如果要给预览视图设置指定的大小，请在surfaceChanged()方法中像上面的注释中提到的一样设置。当设置预览视图大小时，必须使用从getSupportedPreviewSizes()获取到的值。不要在setPreviewSize()中随意设置值。
     *
     * @param holder
     * @param format
     * @param w
     * @param h
     */
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // 如果预览视图可变或者旋转，要在这里处理好这些事件
        // 在重置大小或格式化时，确保停止预览

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // 变更之前要停止预览
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // 在这里重置预览视图的大小、旋转、格式化

        // 使用新设置启动预览视图
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            DebugLog.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    private Camera.Size getPropPreviewSize(List<Camera.Size> supportedPreviewSizes) {
        float ratio=0.1f;
//        float widthHeightRatio= VideoMakerConfig.DPI_WIDTH*1.0f/ VideoMakerConfig.DPI_HEIGHT;
        float widthHeightRatio= getMeasuredWidth()*1.0f/ getMeasuredHeight();
        int maxWidth=0;
        Camera.Size sizeResult=supportedPreviewSizes.get(0);
        for (Camera.Size size:supportedPreviewSizes){
            if (Math.abs(widthHeightRatio-size.width*1.0f/size.height)<ratio && size.width>maxWidth){
                sizeResult=size;
                maxWidth=size.width;
            }
        }
        return sizeResult;
    }
}
